<template>
  <div class="page ">
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
      <el-tab-pane label="进入招标环节" name="1">

      </el-tab-pane>
      <el-tab-pane label="已发布招标公告" name="2">

      </el-tab-pane>
      <el-tab-pane label="今日开标" name="3">

      </el-tab-pane>
      <el-tab-pane label="已完成招标" name="4">

      </el-tab-pane>
      <el-tab-pane label="采购管理" name="5">

      </el-tab-pane>
      <el-tab-pane label="费用报销" name="6">
        <PurchaseClaimList />
      </el-tab-pane>
    </el-tabs>

    <div v-if="activeName!='6'">
      <el-form :inline="true" v-if="searchVisible" class="query-form m-b-10" ref="searchForm" :model="searchForm" @keyup.enter="refreshList()" @submit.prevent>
        <el-form-item prop="project.id" label="所属项目：">
          <GridSelect title="选择所属项目" placeholder="请选择所属项目" labelName='projectName' labelValue='id' v-model="searchForm.project.id" :limit="1" :columns="[ {
						    prop: 'projectNo',
						    label: '项目编号'
						  },
						  {
						    prop: 'projectName',
						    label: '项目名称'
						  }]" :searchs="[{prop: 'projectNo',label: '项目编号'	},{	prop: 'projectName',	label: '项目名称'}]" :api="projectMainService">
          </GridSelect>
        </el-form-item>

        <el-form-item prop="manageDepartment.id" label="管理部门：">
          <office-select v-model="searchForm.manageDepartment.id" type="2" />
        </el-form-item>
        <el-form-item prop="executeDepartment.id" label="承办部门：">
          <office-select v-model="searchForm.executeDepartment.id" type="2" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="refreshList()" icon="search">查询</el-button>
          <el-button type="default" @click="resetSearch()" icon="refresh-right">重置</el-button>
        </el-form-item>
      </el-form>

      <div class="jp-table">
        <vxe-toolbar ref="PurchaseListChildToolbar" :refresh="{query: refreshList}" import export print custom>

          <template #tools>
            <vxe-button type="text" :title="
		    searchVisible ? '收起检索' : '展开检索'
		  " icon="vxe-icon-search" class="tool-btn" @click="searchVisible = !searchVisible"></vxe-button>
            <vxe-button type="text" title="下载导入模板" v-if="hasPermission('child:projectChild:import')" icon="vxe-button--icon vxe-icon-file-excel"
              class="tool-btn m-l-0" @click="downloadTpl()">
            </vxe-button>
          </template>
        </vxe-toolbar>

        <div class="jp-table-body">
              <vxe-table border auto-resize resizable height="600" :loading="loading" size="small" ref="purchaseTable" show-header-overflow show-overflow
            highlight-hover-row :menu-config="{}" :print-config="{}"
            :import-config="{    importMethod: importMethod,    types: ['csv', 'xls', 'xlsx'],    remote: true,  }" :export-config="{    remote: true,    filename: `采购主表数据${moment(new Date()).format(
		'YYYY-MM-DD'
    )}`,
    sheetName: '采购主表数据',
    exportMethod: exportMethod,
    types: ['xlsx'],
    modes: ['current', 'selected', 'all'],
  }" @sort-change="sortChangeHandle" :expand-config="{accordion: true, lazy: true,loadMethod:detail}" :sort-config="{remote:true}"  :data="dataList" :checkbox-config="{}">
            <vxe-column type="seq" width="40"></vxe-column>
            <vxe-column type="checkbox" width="40px"></vxe-column>            
            <vxe-column type="expand" width="80" v-if="activeName=='3'">
              <template #content="{ row }">
                <el-tabs class="child-tab">
              
                  <el-tab-pane label="报名情况(报名单位名称)" >
                    <el-table :data="row.purchaseTenderFirmDTOList" class="child-table" border>
                      <el-table-column prop="company.companyName" align="center" header-align="center" label="报名单位">
                      </el-table-column>
                      <el-table-column prop="contactPerson" show-overflow-tooltip align="center" header-align="center" label="联系人">
                      </el-table-column>
                      <el-table-column prop="contactPhone" show-overflow-tooltip align="center" header-align="center" label="联系电话">
                      </el-table-column>
                    </el-table>
                  </el-tab-pane>
                </el-tabs>
              </template>
            </vxe-column>


          
        <vxe-column field="project.projectName" title="项目名称（上游项目）" width="400px">
              <template #default="{ row }">

                <el-link type="primary" :underline="false" v-if="hasPermission('purchase:purchase:edit')"
                  @click="initView(row.id)">{{row.project &&  row.project.projectName}}</el-link>
                <span v-else>{{row.project && row.project.projectName}}</span>
              </template>
            </vxe-column>

            
            <vxe-column field="purchaseName" title="采购(项目)名称" width="300px">
            </vxe-column>
            <vxe-column field="purchaseType" width="100px" title="类型">
              <template #default="{ row }">
                {{ $dictUtils.getDictLabel("purchase_type", row.purchaseType, '-') }}
              </template>
            </vxe-column>
            <vxe-column field="purchaseRange" title="招标（采购）范围或内容" width="200px">
            </vxe-column>
            <vxe-column field="limitPrice" sortable title="招标（采购）限价（元）" width="140px">
            </vxe-column>
                  <vxe-column field="orgForm" sortable title="招标组织形式" width="140px">
              <template #default="{ row }">
                {{ $dictUtils.getDictLabel("org_form", row.orgForm, '-') }}
              </template>
            </vxe-column>
            <vxe-column field="purchaseWay" title="招标(采购)方式" width="140px">
              <template #default="{ row }">
                {{ $dictUtils.getDictLabel("procurement_method", row.purchaseWay, '-') }}
              </template>
            </vxe-column>
                <vxe-column field="manageDepartment.name" sortable title="管理部门" width="140px">
              <template #default="{ row }">
                {{row.manageDepartment && row.manageDepartment.name}}
              </template>
            </vxe-column>

            <vxe-column field="executeDepartment.name" sortable title="承办部门" width="140px"></vxe-column>
            <vxe-column field="executeLeader.name" title="承办人" width="140px"> </vxe-column>


        
           <vxe-column field="tender.tenderNoticeTime" title="公告发布时间" v-if="activeName!='1'&&activeName!='4'" width="160px">
            </vxe-column>
              <vxe-column field="tender.tenderNotice" sortable title="附件" width="160px" v-if="activeName!='1'&&activeName!='4'">
            <template #default="{ row }">
              <div @click="previewFiles(row.tender?.tenderNotice)" class="file">{{getFileName(row.tender?.tenderNotice)}}</div>
            </template>
          </vxe-column>
            <vxe-column field="tender.openBidTime" title="开标时间" v-if="activeName=='2'" width="160px">
            </vxe-column>
            <vxe-column field="tender?.status" title="中标情况" v-if="activeName=='4'" width="140px">
              <template #default="{ row }">
                {{ $dictUtils.getDictLabel("tender_status", row.tender?.status, '-') }}
              </template>
            </vxe-column>
            <vxe-column field="tender?.winBidCompany?.companyName" title="中标单位" v-if="activeName=='4'" width="140px">
            </vxe-column>

            <vxe-column field="tender?.winBidAmount" title="中标金额(元)" v-if="activeName=='4'" width="140px">
            </vxe-column>
          
          
       
     
            <vxe-column fixed="right" align="center" width="240" title="操作">
              <template #default="{ row }">
                <el-button v-if="hasPermission('purchase:purchase:view')" v-show="activeName=='1'" type="primary" text icon="view-filled"
                  @click="addTender(row)">发布招标公告</el-button>
                <el-button v-if="hasPermission('purchase:purchase:edit')" type="primary" v-show="activeName=='2'" text icon="edit-filled"
                  @click="editTender(row.tender.id)">报名单位录入</el-button>
                <el-button v-if="hasPermission('purchase:purchase:edit')" type="primary" v-show="activeName=='3'" text icon="edit-filled"
                  @click="editResult(row.tender.id)">中标结果录入</el-button>

           
                <el-button v-if="hasPermission('purchase:purchase:edit')" type="primary" v-show="activeName=='4'" text icon="edit-filled"
                  @click="bindRestart(row)">重新发起招标</el-button>
                  <el-button v-if="hasPermission('purchase:purchase:view')" type="primary" text icon="view-filled" @click="view(row)" v-show="activeName=='5'" >查看详情</el-button>

                <!--     <el-button v-if="hasPermission('purchase:purchase:edit')" type="primary" v-show="activeName=='4'" text icon="edit-filled"
                  @click="editResult(row.tender.id)">推送至采购管理</el-button> // <el-button v-if="hasPermission('purchase:purchase:view')" type="primary" text icon="view-filled" @click="routerTender(row)">招标</el-button>
              // <el-button v-if="hasPermission('purchase:purchase:view')" type="primary" text icon="view-filled" @click="view(row)">查看详情</el-button>
              //        <el-button v-if="hasPermission('predict:predictContract:addList')" type="warning" text @click="openContractDialog(row)">预计合同登记</el-button> -->

                <el-button v-if="hasPermission('purchase:purchase:edit')" type="primary" text icon="edit-filled" @click="edit(row.id)"
                  v-show="activeName=='5'">修改</el-button>
                <el-button v-if="hasPermission('purchase:purchase:del')" type="danger" text icon="del-filled" @click="del(row.id)"
                  v-show="activeName=='5'">删除</el-button>
              </template>
            </vxe-column>
          </vxe-table>
          <vxe-pager background size="small" :current-page="tablePage.currentPage" :page-size="tablePage.pageSize" :total="tablePage.total"
            :page-sizes="[10, 20, 100, 1000, {label: '全量数据', value: 1000000}]" :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
            @page-change="currentChangeHandle">
          </vxe-pager>
        </div>
      </div>
    </div>

    <!-- 弹窗, 新增 / 修改 -->
    <PurchaseTenderForm ref="purchaseTenderForm" @refreshDataList="refreshList"></PurchaseTenderForm>

    <!-- 弹窗, 新增 / 修改 -->
    <PurchaseForm ref="purchaseForm" @refreshDataList="refreshList"></PurchaseForm>

    <!-- 预计合同登记弹窗 -->
    <el-dialog v-model="contractDialogVisible" title="添加预计合同数" width="800px" :destroy-on-close="true">
      <el-form ref="contractForm" :model="contractForm" label-width="120px" :rules="contractRules">

        <el-table :data="contractForm.contracts" border>
          <el-table-column label="类型" width="80" align="center">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column label="合同类别" prop="contractCategory">
            <template #default="scope">
              <el-select v-model="scope.row.contractCategory" placeholder="请选择合同类别" style="width: 100%">
                <el-option v-for="dict in $dictUtils.getDictList('contract_type')" :key="dict.value" :label="dict.label" :value="dict.value">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="数量" width="200" align="center">
            <template #default="scope">
              <el-input-number v-model="scope.row.planCount" :min="1" controls-position="right" size="small"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" align="center">
            <template #default="scope">
              <div class="pointer" @click="removeContract(scope.$index)">删除</div>
            </template>
          </el-table-column>
        </el-table>

        <div class="text-center" style="margin-top: 20px; text-align: center;">
          <el-button type="info" plain @click="addNewContract" style="width:100%"> 新增</el-button>
        </div>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="contractDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveContract">保 存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 引入抽屉组件 -->
    <purchase-drawer ref="purchaseDrawer" :purchaseId="purchaseId" :projectId="projectId" />
    <!-- 引入文件预览组件 -->
    <FilePreview ref="filePreview" />
  </div>
</template>

<script>
import PurchaseTenderForm from '../tender/PurchaseTenderForm'
import PurchaseForm from './PurchaseForm'
import purchaseService from '@/api/purchase/purchaseService'
import GridSelect from '@/components/gridSelect'
import OfficeSelect from '@/components/officeSelect'
import projectMainService from '@/api/project/projectMainService'
import PurchaseDrawer from './purchaseDrawer.vue'
import predictContractService from '@/api/predict/predictContractService'
import FilePreview from '@/components/preview'
import PurchaseClaimList from '../claim/PurchaseClaimList'
import purchaseTenderService from '@/api/tender/purchaseTenderService'
export default {
  data() {
    return {
      searchVisible: true,
      searchForm: {
        project: {
          id: ''
        },
        purchaseName: '',
        purchaseType: '',
        orgForm: '',
        purchaseWay: '',
        manageDepartment: {
          id: ''
        },
        executeDepartment: {
          id: ''
        }
      },
      projectMainService: projectMainService,
      dataList: [],
      tablePage: {
        total: 0,
        currentPage: 1,
        pageSize: 10,
        orders: [{ column: "a.create_time", asc: false }],
      },
      loading: false,
      contractDialogVisible: false,
      contractForm: {
        purchaseId: '',
        purchaseName: '',
        contracts: [
        ]
      },
      contractRules: {
        purchaseName: [
          { required: true, message: '请输入采购项目名称', trigger: 'blur' }
        ]
      },
      defaultContractTypes: ['材料', '施工服务', '技术服务', '车辆租赁', '安全设施', '保通设施', '保险', '其它'],
      projectId: '',
      purchaseId: "",
      activeName: '1'
    }
  },
  components: {
    GridSelect,
    OfficeSelect,
    PurchaseForm,
    PurchaseDrawer,
    FilePreview,
    PurchaseClaimList,
    PurchaseTenderForm
  },
  created() {
    this.refreshList()
  },
  mounted() {
    this.$nextTick(() => {
      // 将表格和工具栏进行关联
      const $table = this.$refs.purchaseTable
      const $toolbar = this.$refs.PurchaseListChildToolbar
      $table.connect($toolbar)
    })
  },

  methods: {
    // 获取数据列表
    refreshList() {
      this.loading = true
      purchaseService.list({
        'current': this.tablePage.currentPage,
        'size': this.tablePage.pageSize,
        'orders': this.tablePage.orders,
        tenderStatus: this.activeName == 5 ? 4 : this.activeName,
        ...this.searchForm
      }).then((data) => {

        this.dataList = data.records


        this.tablePage.total = data.total
        this.loading = false
      })
    },
    handleClick(val) {
      this.tablePage.currentPage = 1;
      this.activeName = val.props.name;
      this.refreshList()
    },
    // 新增
    addTender(row) {
      this.$refs.purchaseTenderForm.init('add', { purchase: { id: row.id }, project: { id: row.project.id }, type: 1 })
    },
    // 当前页
    currentChangeHandle({ currentPage, pageSize }) {
      this.tablePage.currentPage = currentPage
      this.tablePage.pageSize = pageSize
      this.refreshList()
    },
        // 查看详情
    detail({ row }) {
      return new Promise(resolve => {
        purchaseTenderService.queryById(row.tender.id).then((data) => {
          this.dataList.forEach((item) => {
            if (item.id === row.id) {
              item.purchaseTenderFirmDTOList = data.purchaseTenderFirmDTOList
            }
          })
          resolve()
        })
      })
    },
    // 排序
    sortChangeHandle(obj) {
      this.tablePage.orders = [];
      if (obj.order != null) {
        this.tablePage.orders = [{ column: obj.column.sortBy || this.$utils.toLine(obj.property), asc: obj.order === "asc" }];
      } else {
        this.tablePage.orders = [{ column: "a.create_time", asc: false }];
      }
      this.refreshList();
    },
    // 新增
    add() {
      this.$refs.purchaseForm.init('add', this.searchForm.project.id)
    },
    initView(id) {
      this.$refs.purchaseForm.init('view', id)
    },
    editTender(id) {
      this.$refs.purchaseTenderForm.init('edit', id, 2)

    },
    editResult(id) {
      this.$refs.purchaseTenderForm.init('edit', id, 3)

    },
    // 修改
    edit(id) {
      id = id || this.$refs.purchaseTable.getCheckboxRecords().map(item => {
        return item.id
      })[0]
      this.$refs.purchaseForm.init('edit', id)
    },
    // 查看
    view(row) {
      this.projectId = row.project.id;
      this.purchaseId = row.id;
      this.$refs.purchaseDrawer.open({ id: row.id, projectId: row.project.id })
    },
    // 删除
    del(id) {
      let ids = id || this.$refs.purchaseTable.getCheckboxRecords().map(item => {
        return item.id
      }).join(',')
      this.$confirm(`确定删除所选项吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        purchaseService.delete(ids).then((data) => {
          this.$message.success(data)
          this.refreshList()
          this.loading = false
        })
      })
    },
    bindRestart(row) {
      purchaseService.reboot({ purchaseId: row.id, tenderId: row.tender.id }).then(res => {
        this.$message.success('重新发起招标成功')
        this.refreshList()
      })
    },
    // 下载模板
    downloadTpl() {
      this.loading = true
      purchaseService
        .exportTemplate()
        .then((data) => {
          // 将二进制流文件写入excel表，以下为重要步骤
          this.$utils.downloadExcel(data, "采购主表导入模板");
          this.loading = false
        })
        .catch(function (err) {
          this.loading = false
          if (err.response) {
            console.log(err.response);
          }
        });
    },
    showRouteFee() {
      this.$router.push('/claim/PurchaseClaimList')
    },
    // 自定义服务端导入
    importMethod({ file }) {
      // 处理表单
      const formBody = new FormData();
      formBody.append("file", file);
      this.loading = true
      purchaseService.importExcel(formBody).then((result) => {
        this.$message.success({
          dangerouslyUseHTMLString: true,
          message: result,
        });
        this.refreshList();
      });
    },
    // 自定义服务端导出
    exportMethod({ options }) {
      // 传给服务端的参数
      const params = {
        current: this.tablePage.currentPage,
        size: this.tablePage.pageSize,
        orders: this.tablePage.orders,
        ...this.searchForm,
        filename: options.filename,
        sheetName: options.sheetName,
        isHeader: options.isHeader,
        original: options.original,
        mode: options.mode,
        tenderStatus: this.activeName == 5 ? 4 : this.activeName,
        selectIds:
          options.mode === "selected"
            ? options.data.map((item) => item.id)
            : [],
        exportFields: options.columns.map(
          (column) => column.property && column.property.split(".")[0]
        ),
      };
      this.loading = true;
      return purchaseService
        .exportsRecord(params)
        .then((data) => {
          // 将二进制流文件写入excel表，以下为重要步骤
          this.$utils.downloadExcel(data, options.filename);
          this.loading = false;
        })
        .catch(function (err) {
          if (err.response) {
            console.log(err.response);
          }
        });
    },
    resetSearch() {
      this.$refs.searchForm.resetFields()
      this.refreshList()
    },
    // 打开合同登记弹窗
    openContractDialog(row) {
      this.projectId = row.project.id;
      this.purchaseId = row.id;


      // 加载现有合同数据
      this.loadContractData(row.id)
    },

    // 加载合同数据
    loadContractData(purchaseId) {

      this.loading = true
      predictContractService.findByPurchaseId(purchaseId).then((data) => {
        data.forEach(item => {
          if (!item.project) {
            item.project = { id: this.projectId }
            item.purchase = { id: this.purchaseId }
          }

        })
        this.contractForm.contracts = data;
        this.contractDialogVisible = true;
        this.loading = false
      })

    },

    // 添加新合同
    addNewContract() {
      this.contractForm.contracts.push({ "project": { id: this.projectId }, purchase: { id: this.purchaseId }, contractCategory: '', planCount: 1 })


    },

    // 编辑合同
    editContract(row) {
      // 这里可以实现更复杂的编辑逻辑
      
    },

    // 移除合同
    removeContract(index) {
      this.$confirm('确认删除该合同类型?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.contractForm.contracts.splice(index, 1)
        this.$message.success('删除成功')
      }).catch(() => { })
    },
    previewFiles(url) {
      this.$refs.filePreview.open(url)
    },

    // 保存合同
    saveContract() {
      this.$refs.contractForm.validate(valid => {
        if (!valid) return

        this.loading = true

        // 这里应该调用API保存合同数据
        // 示例实现：
        purchaseService.listSave({ list: this.contractForm.contracts }).then(res => {
          this.$message.success('保存成功')
          this.contractDialogVisible = false
          this.refreshList()
          this.loading = false
        })


      })
    },
    routerTender(row) {
      this.$router.push({ path: '/tender/PurchaseTenderList', query: { purchaseId: row.id, projectId: row.project.id, purchaseWay: row.purchaseWay, orgForm: row.orgForm } })
    },
        getFileName(attachment) {
      if (!attachment) return '';
      if (attachment.indexOf('&fileName=') != -1) {
        return attachment
          .split(',')
          .map(item => {
            const arr = item.split('&fileName=');
            return arr.length > 1 ? arr[1] : '';
          })
          .filter(Boolean)
          .join(', ');
      } else {
        return attachment
          .split(',')
          .map(item => {
            const arr = item.split('&name=');
            return arr.length > 1 ? arr[1] : '';
          })
          .filter(Boolean)
          .join(', ');
      }

    },
    getFileName(attachment) {
      if (!attachment) return '';
      if (attachment.indexOf('&fileName=') != -1) {
        return attachment
          .split(',')
          .map(item => {
            const arr = item.split('&fileName=');
            return arr.length > 1 ? arr[1] : '';
          })
          .filter(Boolean)
          .join(', ');
      } else {
        return attachment
          .split(',')
          .map(item => {
            const arr = item.split('&name=');
            return arr.length > 1 ? arr[1] : '';
          })
          .filter(Boolean)
          .join(', ');
      }

    },
  }
}
</script>

<style lang="scss" scoped>
.text-center {
  text-align: center;
}
.child-tab{
  width: calc(100% - 200px);
  overflow: hidden;
  padding-left: 0;
  padding-right: 0;
}
:deep(.el-tabs__header){
  padding-left: 12px;
}
</style>
<style></style>

